package com.example.mydata.service;


import com.example.mydata.Exception.LibraryException;
import com.example.mydata.Vo.Book;
import com.example.mydata.Vo.BookStatus;
import com.example.mydata.Vo.User;
import org.springframework.stereotype.Service;

@Service
public class LibraryService {

    // 借书逻辑
    public boolean borrowBook(User user, Book book) {
        // 条件判断：
        // 1. 书籍状态为AVAILABLE
        // 2. 库存 > 0
        // 3. 用户当前借书未超过3本
        if (book.getStatus() == BookStatus.AVAILABLE
                && book.getStock() > 0
                && user.getBorrowedBooks().size() < 3) {
            book.setStock(book.getStock() - 1);
            if (book.getStock() == 0) {
                book.setStatus(BookStatus.BORROWED);
            }
            user.getBorrowedBooks().add(book);
            return true;
        }
        return false;
    }

    public int returnBook(User user, Book book) throws LibraryException {
        if (!user.getBorrowedBooks().contains(book)) {
            throw new LibraryException("用户未借过此书");
        }
        if (book.getStatus() != BookStatus.BORROWED) {
            throw new LibraryException("书籍状态不正确");
        }
        book.setStock(book.getStock() + 1);
        if (book.getStock() > 0) {
            book.setStatus(BookStatus.AVAILABLE);
        }
        user.getBorrowedBooks().remove(book);
        return user.getBorrowedBooks().size();
    }

    public Book selectBookById(String bookId) {
        // 从数据库中查询书籍信息的逻辑
        // 模拟返回一个Book对象
        return new Book();
    }
}